package com.example.steveaoblogdemo.service.impl;

import com.example.steveaoblogdemo.config.QiNiuConfig;
import com.example.steveaoblogdemo.service.QiNiuUpload;
import com.example.steveaoblogdemo.utils.QiNiuUtil;
import com.example.steveaoblogdemo.utils.Result;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class QiNiuUploadImpl{


    private QiNiuConfig qiNiuConfig;


    /**七牛认证管理 */
    private Auth auth;

    private UploadManager uploadManager;
    private BucketManager bucketManager;
    private String token;

    private QiNiuUploadImpl(QiNiuConfig qiNiuConfig){
        this.qiNiuConfig = qiNiuConfig;
        init();
    }

    private void init(){
        /**七牛文件上传管理器 */
        uploadManager = new UploadManager(new Configuration(Zone.zone2()));
        auth = Auth.create(qiNiuConfig.getAccessKey(),qiNiuConfig.getSecretKey());
        bucketManager = new BucketManager(auth, new Configuration(Zone.zone2()));
        token = auth.uploadToken(qiNiuConfig.getBucketName());
    }

    public String uploadPicture(MultipartFile file) {
        try{
            String fileName = file.getOriginalFilename();
            String randomImageName = QiNiuUtil.getRandomImageName(fileName);

            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            //获取BufferImage的属性，避免输入的是空照片
            if (bufferedImage == null||bufferedImage.getHeight() == 0 ||bufferedImage.getWidth() == 0){
                return "上传失败";
            }
            //上传
            Response response = uploadManager.put(file.getInputStream(),randomImageName,token,null,null);
            if (response.isOK()){
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
                //返回的是上传图片的文件名
                return putRet.key;

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        
        return null;
    }


    public String getPrivateFile(String fileKey) {
        String encodedFileName = null;
        String finalUrl = null;
        try {
            encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
            String publicUrl = String.format("%s/%s", this.qiNiuConfig.getFileDomain(), encodedFileName);
            //1小时，可以自定义链接过期时间
            long expireInSeconds = 3600;
            finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return finalUrl;
    }



    public boolean removeFile(String bucketName, String fileKey) {
        try {
            bucketManager.delete(bucketName, fileKey);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return true;
    }


}
